import { LoadIcon } from '@/components/bs-icons/loading'
import { CodeBlock } from '@/modals/formModal/chatMessage/codeBlock'
import { copyText } from '@/utils'
import { ReloadIcon } from '@radix-ui/react-icons'
import type { CollapseProps } from 'antd'
import { Collapse } from 'antd'
import { useEffect, useMemo, useRef, useState } from 'react'
import ReactMarkdown from 'react-markdown'
import rehypeMathjax from 'rehype-mathjax/svg'
import remarkGfm from 'remark-gfm'
import remarkMath from 'remark-math'
import LlmIcon from './LlmIcon'
import MessageBs_knowledgeList from './MessageBs_knowledgeList'
import './styles.less'
import { ContentType } from './types'

// 颜色列表
const colorList = [
  '#111111',
  '#FF5733',
  '#3498DB',
  '#27AE60',
  '#E74C3C',
  '#9B59B6',
  '#F1C40F',
  '#34495E',
  '#16A085',
  '#E67E22',
  '#95A5A6'
]
// 定义正则表达式，用于匹配 ^[数字]^ 模式的文本，允许多个连续匹配
const regex = /\^(\[\d+\])+?\^/g

export default function MessageBs({
  data,
  onUnlike = () => {},
  onSource,
  backGrou,
  citations,
  chatting,
  nextDataInfo
}: {
  data: ContentType | any
  onUnlike?: any
  onSource?: any
  backGrou: string
  citations?: any
  chatting: string
  nextDataInfo?: any
}) {
  useEffect(() => {
    console.log('MessageBs: ', data)
  }, [data])

  let msg = data.type === 'image_url' ? data.image_url?.url : data.text
  if (data.type === 'text') {
    try {
      msg = msg.replace(regex, match => {
        // 没用溯源不显示溯源^[1][2]^这种数据
        if (!data?.internetCitations || data?.internetCitations?.length === 0) {
          return ''
        }
        const innerContent = match.slice(1, -1)
        const numbers = innerContent.split('][').map(numStr => {
          const cleanedNumStr = numStr.replace(/^\[|\]$/g, '')
          const num = parseInt(cleanedNumStr, 10)
          if (isNaN(num) || !data?.internetCitations?.[num - 1]) {
            return `[${numStr}]`
          }
          return `[[${num}]](${data?.internetCitations[num - 1]?.url})`
        })
        return numbers.join('')
      })
    } catch (error) {
      console.error('Error during message replacement:', error)
    }
  }

  /* 上一条信息判断重发 */
  const handleResend = send => {
    const nextData = nextDataInfo.nextData
    if (!nextData) return
    // 获取文本 
    const text = nextData?.content?.filter(item => item.type === 'text').map(item => item.text)

    // 获取图片
    const imageUrl = nextData?.content?.filter(item => item.type === 'image_url').map(item => item.image_url?.url)
    const imageName = nextData?.content?.filter(item => item.type === 'image_url').map(item => item.image_url?.name)
    
    // 获取文件列表
    const files = nextData?.content?.filter(item => item.type === 'file_url').map(item => ({
      url: item.file_url?.url || '',
      name: item?.file_url?.name || ''
    }))

    const myEvent = new CustomEvent('userResendMsgEvent', {
      detail: {
        send,
        message: text||'',
        imageUrl: imageUrl||'',
        imageName: imageName||'',
        files: files||[]
      }
    })
    document.dispatchEvent(myEvent)
  }

  const avatarColor = colorList[0]
  const mkdown = useMemo(
    () => (
      <ReactMarkdown
        remarkPlugins={[remarkGfm, remarkMath]}
        rehypePlugins={[rehypeMathjax]}
        linkTarget="_blank"
        className="bs-mkdown inline-block max-w-full whitespace-break-spaces break-all text-sm text-text-answer"
        components={{
          code: ({ node, inline, className, children, ...props }) => {
            if (children.length) {
              if (children[0] === '▍') {
                return <span className="form-modal-markdown-span"> ▍ </span>
              }

              children[0] = (children[0] as string).replace('`▍`', '▍')
            }

            const match = /language-(\w+)/.exec(className || '')

            return !inline ? (
              <CodeBlock
                key={Math.random()}
                language={(match && match[1]) || ''}
                value={String(children).replace(/\n$/, '')}
                {...props}
              />
            ) : (
              <code className={className} {...props}>
                {' '}
                {children}{' '}
              </code>
            )
          }
        }}
      >
        {msg.toString()}
      </ReactMarkdown>
    ),
    [data.type, data.image_url?.url, data.text]
  )

  const messageRef = useRef<HTMLDivElement>(null)
  const handleCopyMessage = () => {
    copyText(messageRef.current)
  }

  const internetCitationsList = () => {
    return (
      <Collapse
        className="mb-[8px]"
        size="small"
        items={[
          {
            key: '1',
            label: `找到了${data.internetCitations.length}篇资料作为参考`,
            children: (
              <div className="flexCol">
                {data?.internetCitations?.length > 0 &&
                  data.internetCitations.map((item, index) => {
                    return (
                      <div key={index} className="mt-[4px]">
                        <a
                          href={item.url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="inline-block cursor-pointer text-blue-500"
                        >
                          {index + 1}. {item.title}
                        </a>
                      </div>
                    )
                  })}
              </div>
            )
          }
        ]}
      />
    )
  }

  const [activeKey, setActiveKey] = useState<string[]>(['1'])
  const ThinkItemLabel = (
    <div className="bs-think-item-label">
      <div>{data?.text ? `已深度思考${data?.thinkTime ? `（用时${data.thinkTime}秒）` : ''}` : '思考中...'}</div>
      <div>
        {activeKey.length ? (
          <svg width="16" height="16" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M6 8L10 12L14 8" stroke="black" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        ) : (
          <svg width="16" height="16" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M8 14L12 10L8 6" stroke="black" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        )}
      </div>
    </div>
  )

  const ThinkItem: CollapseProps['items'] = [
    {
      key: '1',
      label: ThinkItemLabel,
      children: (
        <div>
          <div className="bs-think-collapse-left"></div>
          <div className="bs-think-collapse-content inline-block max-w-full whitespace-break-spaces break-all text-text-answer">
            {data?.think}
          </div>
        </div>
      ),
      showArrow: false
    }
  ]

  return (
    <div className="flex w-full py-1">
      <div className="w-fit max-w-[90%]">
        {/* <div className="w-fit max-w-[688px]"> */}
        {/* {data.sender && <p className="mb-2 text-xs text-gray-600">{data.sender}</p>} */}
        <div className="flex gap-[12px]">
          <LlmIcon avatarColor={avatarColor} />
          <span className="chat-role-name">智能助手</span>
        </div>
        <div
          className={`chat-custom-content ml-[34px] min-h-8 rounded-[12px] bg-[#F5F7FB] p-[16px] dark:bg-[#313336] ${backGrou}`}
        >
          <div className={msg.toString() ? 'flex gap-2' : 'flexRowStart gap-2'}>
            {msg || data?.think ? (
              <div ref={messageRef} className="max-w-[100%] text-sm">
                {/* 联网展示信息 */}
                {data?.internetCitations?.length > 0 && internetCitationsList()}
                {data?.think && (
                  <Collapse
                    className="bs-think-collapse"
                    defaultActiveKey={['1']}
                    ghost
                    items={ThinkItem}
                    onChange={(key: any) => {
                      setActiveKey(key)
                    }}
                  />
                )}

                {/* 内容 */}
                {mkdown}
                {/* 知识库  插件 引用列表 */}
                {citations?.length > 0 && citations[0]?.type != 'internet' && (
                  <MessageBs_knowledgeList
                    title={`${citations[0].type === 'plugin' ? '' : `引用知识库（${citations.length}）`}`}
                    list={citations}
                  ></MessageBs_knowledgeList>
                )}
                {/* @user */}
                {/* {data.receiver && <p className="text-sm text-blue-500">@ {data.receiver.user_name}</p>} */}
                {/* 光标 */}
                {/* {data.message.toString() && !data.end && <div className="animate-cursor absolute w-2 h-5 ml-1 bg-gray-600" style={{ left: cursor.x, top: cursor.y }}></div>} */}
                <br />
                {data?.chatStopTag && <div className="chatStopSize mt-[12px]">已停止生成</div>}
              </div>
            ) : (
              <div>
                <LoadIcon className="text-gray-400" />
              </div>
            )}
          </div>
        </div>
        {/* 
            chatting = again 回答结束 = stop 回答中 = '' 接受消息中
            nextDataInfo.nextData 判断上一条 != 第一条
            nextDataInfo.index MaxLength 最后一条显示icon功能
        */}
        {chatting === 'again' &&
          nextDataInfo.nextData &&
          nextDataInfo.index !== 0 &&
          nextDataInfo.index === nextDataInfo.MaxLength - 1 && (
            <div
              className="flexRowStart chatMessageBotSize cursonCase ml-[34px] mt-[6px]"
              onClick={() => handleResend(true)}
            >
              <ReloadIcon className="mr-[4px] hover:text-gray-500" />
              重新生成
            </div>
          )}
        {chatting === 'stop' &&
          nextDataInfo.nextData &&
          nextDataInfo.index !== 0 &&
          nextDataInfo.index === nextDataInfo.MaxLength - 1 && (
            <div
              className="flexRowStart chatMessageBotSize cursonCase ml-[34px] mt-[6px]"
              onClick={() => handleResend('stop')}
            >
              <svg
                width="14"
                height="14"
                viewBox="0 0 14 14"
                className="mr-[4px]"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <g clipPath="url(#clip0_387_17616)">
                  <path
                    fillRule="evenodd"
                    clipRule="evenodd"
                    d="M1.5 7C1.5 3.96243 3.96243 1.5 7 1.5C10.0376 1.5 12.5 3.96243 12.5 7C12.5 10.0376 10.0376 12.5 7 12.5C3.96243 12.5 1.5 10.0376 1.5 7ZM7 0.5C3.41015 0.5 0.5 3.41015 0.5 7C0.5 10.5899 3.41015 13.5 7 13.5C10.5899 13.5 13.5 10.5899 13.5 7C13.5 3.41015 10.5899 0.5 7 0.5ZM6 5C5.44772 5 5 5.44772 5 6V8C5 8.55229 5.44772 9 6 9H8C8.55229 9 9 8.55229 9 8V6C9 5.44772 8.55229 5 8 5H6Z"
                    fill="#7587A5"
                  />
                </g>
                <defs>
                  <clipPath id="clip0_387_17616">
                    <rect width="14" height="14" fill="white" />
                  </clipPath>
                </defs>
              </svg>
              停止生成
            </div>
          )}
      </div>
    </div>
  )
}
